package com.example.xialingfeng

import android.content.Intent
import android.os.Bundle
import android.view.Menu
import android.view.MenuItem
import android.widget.Button
import android.widget.EditText
import android.widget.TextView
import androidx.appcompat.app.AppCompatActivity

class MainActivity : AppCompatActivity() {
    private lateinit var etNumber1: EditText
    private lateinit var etNumber2: EditText
    private lateinit var tvResult: TextView
    private lateinit var history: MutableList<String>

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        title = "Xia Lingfeng 2022110346" // Replace with your name and student ID

        etNumber1 = findViewById(R.id.etNumber1)
        etNumber2 = findViewById(R.id.etNumber2)
        tvResult = findViewById(R.id.tvResult)
        history = mutableListOf()

        findViewById<Button>(R.id.btnAdd).setOnClickListener { performOperation("+") }
        findViewById<Button>(R.id.btnSubtract).setOnClickListener { performOperation("-") }
        findViewById<Button>(R.id.btnMultiply).setOnClickListener { performOperation("*") }
        findViewById<Button>(R.id.btnDivide).setOnClickListener { performOperation("/") }
    }

    private fun performOperation(op: String) {
        val num1 = etNumber1.text.toString().toDoubleOrNull()
        val num2 = etNumber2.text.toString().toDoubleOrNull()
        if (num1 != null && num2 != null) {
            val result = when (op) {
                "+" -> num1 + num2
                "-" -> num1 - num2
                "*" -> num1 * num2
                "/" -> num1 / num2
                else -> 0.0
            }
            tvResult.text = result.toString()
            history.add("$num1 $op $num2 = $result")
            saveHistory()
        }
    }

    override fun onCreateOptionsMenu(menu: Menu?): Boolean {
        menuInflater.inflate(R.menu.menu, menu)
        return true
    }

    override fun onOptionsItemSelected(item: MenuItem): Boolean {
        return when (item.itemId) {
            R.id.menu_history -> {
                val intent = Intent(this, HistoryActivity::class.java)
                startActivity(intent)
                true
            }
            else -> super.onOptionsItemSelected(item)
        }
    }

    private fun saveHistory() {
        val sharedPreferences = getSharedPreferences("history", MODE_PRIVATE)
        val editor = sharedPreferences.edit()
        editor.putStringSet("history_set", history.toSet())
        editor.apply()
    }
}